#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#include "crvm.h"

char disbuf [30];
bool skip_flag = 0;

void show_status (void)
{
	printf ("%6lu  ", instruction_numble); //cyclenumble);
	//	  if (skip_flag)
	//	    strcpy (disbuf, "pipeline stall");
	//	  else
	//	    {
	sprintf (disbuf, "%04x: ", pc);
	disassemble_inst (*((romaddr*)rom+pc), & disbuf [strlen (disbuf)]);
	//	    }
	printf ("%-30s  A=%02x  S=%c%c%c%c%c%c%c%c  ",
		disbuf,
		acc,
		(*sfr & STATUS_GB) ? 'G' : '.',
		(*sfr & STATUS_PG1) ? '1' : '.',
		(*sfr & STATUS_PG0) ? '0' : '.',
		(*sfr & STATUS_WT ) ? 'T' : '.',
		(*sfr & STATUS_SP ) ? 'P' : '.',
		(*sfr & STATUS_Z  ) ? 'Z' : '.',
		(*sfr & STATUS_AC ) ? 'D' : '.',
		(*sfr & STATUS_C  ) ? 'C' : '.'
		);
	//	  (int) tmr0);
	printf ("\n");
}



int main(int argc,char **argv)
{
	FILE *pf_src;
	char *filename;
	unsigned int len_filename;
	romaddr opcode;
	

	if(argc < 2)
	{
		printf("please input bin file name");
		exit(1);
	}

	filename = (char*) malloc(0);
	len_filename = strlen(argv[1]);
	filename = (char*) malloc (sizeof(char) *( len_filename +1));
	strcpy (filename ,argv[1]);
	pf_src = fopen(filename,"rb");
	initial_hard();

	fread(rom,sizeof(romaddr),MAXROM,pf_src);

	pc = 0x7ff;
	*pcl = (char)0xff;

	while (! quit)
	{
		while (run || step)
		{
			if (step)
				step--;
			if ((! skip_flag) && (! ignore_break) 
				&& (bp_list_find(bplist,pc) != NULL)
				|| (bp_list_find(bpstepover,pc) != NULL)
				)
			{
				printf ("breakpoint reached at %04x\n", pc);
				run = 0;
				step = 0;
			}
			else
			{
				ignore_break = 0;

				opcode = *((romaddr*)rom+pc);
				decode(opcode);
				if (trace && (run || step))
					show_status ();
			}
		}
		show_status ();
		bpstepover = bp_list_remove_all(bpstepover);
		debug ();
	}

	return 0;
}
